<template>
<div>
  <el-table
    header-row-class-name="base-table-header-v3"
    row-class-name="base-table-row-v3"
    :data="data"
    border
    max-height="500">
    <el-table-column type="index" width="50" :label="$t('common.base.SN')" />
    <el-table-column
      v-for="(column, index) in columns"
      :key="`${column.fieldName}_${index}`"
      :label="column.displayName"
      :prop="column.fieldName"
      :show-overflow-tooltip="column.tooltip"
      :width="column.width"
      :fixed='column.isFixed'>
      <template slot-scope="scope">
        <template v-if="column.fieldName === 'serialNumber'">
          {{ scope.row.sn || scope.row.serialNumber }}
        </template>
        <template v-if="['snManage', 'property'].includes(column.fieldName)">
              {{ $t(`task.${scope.row[column.fieldName]}`) }}
        </template>

        <!-- start 小计 -->
        <template v-else-if="column.fieldName === 'total'">
          <span>
            <span>{{ scope.row.salePrice && (scope.row.preNum * scope.row.salePrice).toFixed(2) }}</span>
            <span v-if="internationalGray" class="ml-3">{{scope.row.salePriceCurrency || 'CNY'}}</span>
          </span>
        </template>
        <!-- end 小计 -->

         <!-- start 单价 -->
        <template v-else-if="column.fieldName === 'salePrice'">
          {{ scope.row | fmt_salePrice_currency }}
        </template>
        <!-- end 单价 -->

        <!-- start 预计用量 -->
        <template v-else-if="column.fieldName === 'preNum'">
          <el-input-number v-if="!openDialogMode" v-model="scope.row.preNum" step-strictly controls-position="right" :min="1"></el-input-number>
          <!-- 申领出库弹窗用下面的 -->
          <el-input-number v-else v-model="scope.row.preNum" step-strictly controls-position="right" :min="0" :max="isAllowGtInventory(scope.row)"></el-input-number>
        </template>
        <!-- end 预计用量 -->

        <!-- start 质保 -->
        <template v-else-if="column.fieldName === 'warrantyStatus'">
          <template v-if="allowWarrantyChange && !isOnlyMaterialOut">
            <el-select
              v-model="scope.row.warrantyStatus"
              filterable>
              <el-option
                v-for="item in scope.row.warrantyStatusData"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
          <template v-else>{{ warrantyStatusMap[scope.row.warrantyStatus] }}</template>
        </template>
        <!-- end 质保 -->

        <!-- start 出库仓库 -->
        <template v-else-if="column.fieldName === 'warehouse'">
          <el-select
            @change="chooseWarehouse($event, scope.row, scope.$index)"
            v-model="scope.row.warehouse"
            value-key="value"
            filterable
            :disabled="!allowSelectWarehouse">
            <el-option
              v-for="item in scope.row.warehouseData"
              :key="item.value"
              :label="item.label"
              :value="item">
            </el-option>
          </el-select>
        </template>
        <!-- end 出库仓库 -->

        <!-- start 出库仓位 -->
        <template v-else-if="column.fieldName === 'warehousePosition'">
          <el-select
            @change="chooseWarehousePosition($event, scope.row, scope.$index)"
            v-model="scope.row.warehousePosition"
            value-key="value"
            filterable
            :disabled="!allowSelectWarehouse">
            <el-option
              v-for="item in scope.row.warehousePositionData"
              :key="item.value"
              :label="item.label"
              :value="item">
            </el-option>
          </el-select>
        </template>
        <!-- end 出库仓位 -->

        <!-- start 操作 -->
        <template v-else-if="column.fieldName === 'action'">
          <el-button class="text-danger" type="text" size="mini" @click="data.splice(scope.$index, 1)">{{$t('common.base.delete')}}</el-button>
        </template>
        <!-- end 操作 -->

        <!-- 状态 -->
        <template v-else-if="column.fieldName === 'materialStatus'">
          {{ scope.row.materialStatus ? $t('common.base.open') : $t('common.base.disable') }}
        </template>

        <!-- 富文本 -->
        <template v-else-if="column.formType === 'richtext'">
          <div class='view-detail-btn' @click.stop="openRichtextVisible(scope.row, column)">
            <span v-if="scope.row.attribute[column.fieldName]">{{$t('common.base.view')}}</span>
          </div>
        </template>

        <template v-else>
          <!-- {{ scope.row[column.fieldName] }} -->
          {{ $formatFormField(column, scope.row) }}
        </template>
      </template>
    </el-table-column>
  </el-table>

  <!-- 富文本弹窗 -->
  <base-view-rich-text ref="baseViewRichTextRef"></base-view-rich-text>
</div>
</template>

<script>
/* api */
import * as WareHouseApi from '@src/api/WareHouseApi';
/* model */
import { MATERIAL_LIST_PRENUM_MAX_LENGTH } from '@src/model/const/Number';
import i18n from '@src/locales'
import { useFormMultiLanguage } from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  name: 'material-table',
  props: {
    data: {
      type: Array,
      default: () => ([])
    },
    columns: {
      type: Array,
      default: () => ([])
    },
    border: {
      type: Boolean,
      default: false
    },
    // 区分申领出库/添加并申领状态
    isOnlyMaterialOut: {
      type: Boolean,
      default: false
    },
    // 可选择物料
    canSelectMaterial: {
      type: Boolean,
      default: false
    },
    // 允许物料申领时选择仓库
    allowSelectWarehouse: {
      type: Boolean,
      default: false
    },
    // 允许添加物料时修改物料质保状态
    allowWarrantyChange: {
      type: Boolean,
      default: false
    },
    // 仓库数据集合
    getWarehouseAggregate: {
      type: Object,
      default: () => ({})
    },
    // 判断打开弹窗的方式是 '申领出库' 还是 '添加物料' true 是申领出库、false是添加物料
    openDialogMode: {
      type: Boolean,
      default: false
    },
    // 物料申领配置
    cardConfig: {
      type: Object,
      default: () => ({})
    }
  },
  
  data() {
    return {
      loading: false,
      materialListPreNumMax: MATERIAL_LIST_PRENUM_MAX_LENGTH,
      warrantyStatusMap: {
        0: i18n.t('common.base.warranty'),
        1: i18n.t('common.base.surrender')
      },
      internationalGray
    }
  },
  methods: {
    /**
    * @description 选择仓库
    */
    chooseWarehouse(value, row, index) {
      this.$set(row, 'warehouseId', value.value)
      this.$set(row, 'availableNum', 0)
      this.getDefaultWarehousePosition(row.warehouseId, index)
    },
    /**
    * @description 选择仓位
    */
    chooseWarehousePosition(value, row, rowIndex) {
      this.$set(row, 'positionId', value.value)
      let inventoryParams = {
        warehouseId: row.warehouseId,
        positionId: row.positionId,
        // 物料id需要兼容多个字段名
        materialId: row.relatedId || row.id
      }
      this.getInventoryList(inventoryParams, rowIndex)
    },
    /** 
     * @description 获取默认仓位 
    */
    getDefaultWarehousePosition(warehouseId, index) {
      WareHouseApi.getWarehousePositionSearch({ warehouseId, enabled: true })
        .then((result) => {
          if (result?.success) {
            let data = result?.data || []
            let warehousePositionList = data.map(item => {
              return {
                label: item.name,
                value: item.id
              }
            })
            this.$set(this.data[index], 'warehousePositionData', warehousePositionList)
            // 默认选中第一个仓位
            this.$set(this.data[index], 'warehousePosition', warehousePositionList[0] || {})

            this.$set(this.data[index], 'positionId', warehousePositionList?.[0]?.value)
            // 选择完仓位带出可用库存
            const row = this.data[index];
            let inventoryParams = {
              warehouseId: row.warehouseId,
              positionId: warehousePositionList?.[0]?.value,
              // 物料id需要兼容多个字段名
              materialId: row.relatedId || row.id
            }
            this.getInventoryList(inventoryParams, index)
          }
        }).catch(error => {
          console.error(error);
        })
    },
    /** 
     * @description 获取可用库存 
    */
    getInventoryList(inventoryParams, rowIndex) {
      let params = {
        ...inventoryParams
      }
      WareHouseApi.getInventoryList(params)
        .then(result => {
          if (result?.success) {
            const preNumUpdateEnable = !this.cardConfig.allowGtInventory && this.isOnlyMaterialOut

            let list = result?.data?.list || []
            let idString = this.isOnlyMaterialOut ? 'relatedId' : 'id'
            if(rowIndex != undefined && !list.length){
              this.$set(this.data[rowIndex], 'availableNum', 0)
              // 手动更新预计用量（没有找到库存，预计用量为默认设置为0）
              preNumUpdateEnable && this.$set(this.data[rowIndex], 'preNum', 0)
            }else {
              if(!list.length) {
                this.data.forEach(item => {
                  item.availableNum = 0
                })
              }


              list.forEach(material => {
                let index = this.data.findIndex(item => item[idString] == material.materialId)
                if(index > -1) {
                  this.$set(this.data[index], 'availableNum', material.availableNum)
                  // 手动更新预计用量
                  if (preNumUpdateEnable) {
                    this.$set(this.data[index], 'preNum', Math.min(this.data[index].allowNum, material.availableNum))
                  }
                }
              })
            }
          }
        }).catch(error => {
          console.error(error)
        })
    },
    // 允许申领出库数量大于可用库存数量
    isAllowGtInventory(row) {
      // 允许大于
      if (this.cardConfig.allowGtInventory){
        // 添加并申领 只和可用库存有关。
        return this.isOnlyMaterialOut ? row.allowNum : Infinity;
      }
      // 不允许大于
      // allowNum 允许的最大申领数量
      // availableNum 可用库存
      return this.isOnlyMaterialOut ? Math.min(row.allowNum, row.availableNum) : row.availableNum;
    },
    /** 打开富文本弹窗 */
    openRichtextVisible(row, column) {
      const richtextId = row?.attribute?.[column.fieldName] || ''
      this.$refs?.baseViewRichTextRef?.openDialog(richtextId, false, true);
    }
  }
}
</script>

<style lang="scss" scoped>
input[type="number"],
.el-autocomplete {
  width: 99%;
}

.el-table {
  border-top: 1px solid #e8e8e8;
  border-left: 1px solid #e8e8e8;
}
</style>